# import jenkins
from jenkinsapi.jenkins import Jenkins
import logger
import yaml

# with open('application.yml', 'r') as file:
with open('./jenkinsReport/application.yml', 'r') as file:
    data = yaml.load(file, Loader=yaml.FullLoader)

class JenkinsCo:
    def __init__(self):
        self.url = data['url']
        self.name = data['username']
        self.password = data['password']

    # 连接jenkins服务器，需要参数jenkins登陆地址，用户名，密码
    def __get_connect(self):
        try:
            server = Jenkins(self.url, self.name, self.password)
            return server
        except Exception as E:
            logger.error('连接jenkins服务器失败啦，失败原因{}'.format(E))
            return None

    # 得到上一次构建任务的相关信息
    def get_last_buildnumber(self, project_name):
        server = self.__get_connect()
        if server:
            # 获取job信息
            job_info = server.get_job(project_name)
            return job_info.get_last_buildnumber()
        else:
            return None

    # 拼接allure地址，获取上一次构建成功后allure的地址
    def get_allureadress(self):
        num = self.get_last_buildnumber(data['project_name'])
        if num:
            allure_adress = self.url + 'job/' + data['project_name'] + '/{}/allure/'.format(num)
            return allure_adress
        else:
            return None


if __name__ == '__main__':
    jc = JenkinsCo()
    # key='nextBuildNumber'，获取下一次构建的id
    value = jc.get_allureadress(data['project_name'])
    # print(value)